include .config
ifeq ($(BUILD_TARGET),boot)
include bootloader.mk
else
include application.mk
endif


ifdef GCC_PATH
CC = $(GCC_PATH)/$(PREFIX)gcc
AS = $(GCC_PATH)/$(PREFIX)gcc -x assembler-with-cpp
CP = $(GCC_PATH)/$(PREFIX)objcopy
SZ = $(GCC_PATH)/$(PREFIX)size
else
CC = wine /home/wangkang/.wine/drive_c/Keil_v5/ARM/ARMCC/bin/armcc.exe
AS = wine /home/wangkang/.wine/drive_c/Keil_v5/ARM/ARMCC/bin/armasm.exe
LD = wine /home/wangkang/.wine/drive_c/Keil_v5/ARM/ARMCC/bin/armlink.exe
BIN = wine /home/wangkang/.wine/drive_c/Keil_v5/ARM/ARMCC/bin/fromelf.exe
endif

OPT = -O3

##############
# CFLAGS
##############
CPU = --cpu=Cortex-M0+
MCU = --thumb

C_DEFS = \
-DUSE_HAL_DRIVER \
-DSTM32G030xx

ifeq ($(CONFIG_LYNXI_MCU_CMD_LINE), y)
C_DEFS += -DCONFIG_LYNXI_MCU_CMD_LINE
endif

ifeq ($(CONFIG_LYNXI_MCU_SPI_CMD), y)
C_DEFS += -DCONFIG_LYNXI_MCU_SPI_CMD
endif

ifeq ($(CONFIG_LYNXI_MCU_IAP_UPGRADE), y)
C_DEFS += -DCONFIG_LYNXI_MCU_IAP_UPGRADE
endif

# C includes
C_INCLUDES +=  \
-ICore/Inc \
-IDrivers/STM32G0xx_HAL_Driver/Inc \
-IDrivers/STM32G0xx_HAL_Driver/Inc/Legacy \
-IDrivers/CMSIS/Device/ST/STM32G0xx/Include \
-IDrivers/CMSIS/Include \
-I$(CORE_INC_DIR)

# as flags
ASFLAGS = $(CPU) $(AS_DEFS) $(AS_INCLUDES) \
--pd "__EVAL SETA 1" -g \
--apcs=interwork \
--pd "__MICROLIB SETA 1"

# c flags
CFLAGS = $(CPU) $(C_INCLUDES) $(C_DEFS)\
--c99 -D__EVAL \
-D__MICROLIB \
$(OPT) \
--apcs=interwork \
--split_sections

# ASM sources
ASM_SOURCES =  \
startup/startup_stm32g030xx.s

LDFLAGS = $(CPU) --library_type=microlib --strict --scatter $(SCATTER_FILE)


# default action : build all
all: $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).bin

OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))

OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o)))
vpath %.s $(sort $(dir $(ASM_SOURCES)))

$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR) 
	$(CC) -c $(CFLAGS)  $< -o $@
	
$(BUILD_DIR)/%.o: %.s Makefile | $(BUILD_DIR)
	$(AS) $(ASFLAGS) $< -o $@
	
$(BUILD_DIR)/$(TARGET).elf: $(OBJECTS) Makefile
	$(LD) $(OBJECTS) $(LDFLAGS) -o $@

$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
	$(BIN) $< --bin --output=$@
	
$(BUILD_DIR):
	mkdir $@

.PHONY:clean
clean:
	-rm -rf $(BUILD_DIR)
